﻿using Framework.Infrastructure;
using Framework.Infrastructure.Cache.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Framework.MVC.Infrastructure.Filters
{
    /// <summary>
    /// 授权过滤器（验证手机端接口token）
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class PhoneTokenValidateAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 授权验证的逻辑处理。返回true则通过授权，false则相反，然后进入下面的HandleUnauthorizedRequest方法
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string token = httpContext.Request["token"];
            var b = IsExpireToken(token);
            if (b)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 授权失败处理
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);

            var json = new JsonResult();
            json.Data = new ReturnModel_Common
            {
                success = false,
                code = ReturnCode_System.Token过期或错误,
                msg = "TOKEN_ERROR_OR_EXPIRED"
            };
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            filterContext.Result = json;
        }

        private bool IsExpireToken(string token)
        {
            var model = BaseController.GetPhoneTokenModelByToken(token);
            if (model == null) return false;
            var value = RedisHelper.StringGet(model.Id.ToString(), RedisFolderEnum.PhoneToken);
            if (!string.IsNullOrWhiteSpace(value) && value == token)
            {
                RedisHelper.KeyExpire(model.Id.ToString(), PublicConst.PhoneTokenExpireMins, RedisFolderEnum.PhoneToken);//调用接口就自动延长token过期时间
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}